import 'package:playtruly/common/services/http.dart';
import 'package:playtruly/common/models/report_info_models.dart';
import 'package:playtruly/common/utils/encryption_util.dart';
import 'dart:developer' as developer;

/// 举报相关API
class ReportApi {

  /// 查询举报信息（使用AES加密，基于MyApplication2实现）
  /// [reporterId] 举报者ID（必填）
  /// [page] 页码（可选，默认1）
  /// 返回举报信息列表
  static Future<ReportInfoResponse> getReportInfo({
    required String reporterId,
    int page = 1,
  }) async {
    try {
      developer.log('🔄 =============== 开始查询举报信息（AES加密） ===============');
      developer.log('👤 举报者ID: $reporterId');
      developer.log('📄 页码: $page');

      // 创建请求模型
      final request = ReportInfoRequest(
        reporterId: reporterId,
        page: page,
        timestamp: DateTime.now().millisecondsSinceEpoch ~/ 1000, // 转换为秒级时间戳
      );

      // 获取请求数据
      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密（与MyApplication2保持一致）
      developer.log('🔐 开始AES加密举报信息查询数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /reports/query_by_user/');

      // 发送POST请求（加密）
      final response = await HttpService.to.post(
        '/reports/query_by_user/',
        data: encryptedPayload,
      );

      developer.log('📨 举报信息查询响应: $response');

      // 解析响应
      final reportInfoResponse = ReportInfoResponse.fromJson(response);

      if (reportInfoResponse.isSuccess) {
        developer.log('✅ 举报信息查询成功');
        developer.log('📊 举报数量: ${reportInfoResponse.data?.reports.length ?? 0}');
        if (reportInfoResponse.data?.pagination != null) {
          final pagination = reportInfoResponse.data!.pagination!;
          developer.log('📄 分页信息: 第${pagination.page}页，共${pagination.totalPages}页，总计${pagination.total}条');
        }
      } else {
        developer.log('❌ 举报信息查询失败: ${reportInfoResponse.message ?? "未知错误"}');
      }

      return reportInfoResponse;
    } catch (e) {
      developer.log('💥 查询举报信息异常: $e');
      return ReportInfoResponse(
        status: 'error',
        message: '查询举报信息失败: ${e.toString()}',
      );
    }
  }

  /// 创建举报（使用AES加密，基于MyApplication2实现）
  /// [reporterId] 举报者ID（必填）
  /// [reportType] 举报类型（必填）
  /// [reportReason] 举报原因（必填）
  /// [reportedUserId] 被举报用户ID（可选）
  /// [reportedContentId] 被举报内容ID（可选）
  /// [description] 详细描述（可选）
  /// [reportImages] 举报图片（可选）
  /// [reportLocation] 举报地点（可选）
  /// 返回创建举报结果
  static Future<CreateReportResponse> createReport({
    required int reporterId,
    required String reportType,
    required String reportReason,
    int? reportedUserId,
    int? reportedContentId,
    String? description,
    List<String>? reportImages,
    String? reportLocation,
  }) async {
    try {
      developer.log('🔄 =============== 开始创建举报（AES加密） ===============');
      developer.log('👤 举报者ID: $reporterId');
      developer.log('🎯 举报类型: $reportType');
      developer.log('📝 举报原因: $reportReason');

      // 创建请求模型
      final request = CreateReportRequest(
        reporterId: reporterId,
        reportType: reportType,
        reportReason: reportReason,
        reportedUserId: reportedUserId,
        reportedContentId: reportedContentId,
        description: description,
        reportImages: reportImages,
        reportLocation: reportLocation,
      );

      // 获取请求数据
      final requestData = request.toJson();
      developer.log('📊 请求参数（加密前）: $requestData');
      
      // 🔥 使用AES加密（与MyApplication2保持一致）
      developer.log('🔐 开始AES加密举报创建数据...');
      final encryptedPayload = EncryptionUtil.createEncryptedPayload(requestData);
      
      developer.log('🚀 准备发送加密请求到: /reports/create/');

      // 发送POST请求（加密）
      final response = await HttpService.to.post(
        '/reports/create/',
        data: encryptedPayload,
      );

      developer.log('📨 创建举报响应: $response');

      // 解析响应
      final createReportResponse = CreateReportResponse.fromJson(response);

      if (createReportResponse.isSuccess) {
        developer.log('✅ 举报创建成功: ${createReportResponse.message}');
        if (createReportResponse.reportId != null) {
          developer.log('🆔 举报ID: ${createReportResponse.reportId}');
        }
      } else {
        developer.log('❌ 举报创建失败: ${createReportResponse.message ?? "未知错误"}');
      }

      return createReportResponse;
    } catch (e) {
      developer.log('💥 创建举报异常: $e');
      return CreateReportResponse(
        status: 'error',
        message: '创建举报失败: ${e.toString()}',
      );
    }
  }

  /// 举报用户（便捷方法）
  /// [reporterId] 举报者ID
  /// [reportedUserId] 被举报用户ID
  /// [reportReason] 举报原因
  /// [description] 详细描述（可选）
  static Future<CreateReportResponse> reportUser({
    required int reporterId,
    required int reportedUserId,
    required String reportReason,
    String? description,
  }) async {
    return await createReport(
      reporterId: reporterId,
      reportType: 'user',
      reportReason: reportReason,
      reportedUserId: reportedUserId,
      description: description,
    );
  }

  /// 举报活动（便捷方法）
  /// [reporterId] 举报者ID
  /// [activityId] 活动ID
  /// [reportReason] 举报原因
  /// [description] 详细描述（可选）
  static Future<CreateReportResponse> reportActivity({
    required int reporterId,
    required int activityId,
    required String reportReason,
    String? description,
  }) async {
    return await createReport(
      reporterId: reporterId,
      reportType: 'activity',
      reportReason: reportReason,
      reportedContentId: activityId,
      description: description,
    );
  }

  /// 举报评论（便捷方法）
  /// [reporterId] 举报者ID
  /// [commentId] 评论ID
  /// [reportReason] 举报原因
  /// [description] 详细描述（可选）
  static Future<CreateReportResponse> reportComment({
    required int reporterId,
    required int commentId,
    required String reportReason,
    String? description,
  }) async {
    return await createReport(
      reporterId: reporterId,
      reportType: 'comment',
      reportReason: reportReason,
      reportedContentId: commentId,
      description: description,
    );
  }

  /// 举报内容（便捷方法）
  /// [reporterId] 举报者ID
  /// [contentId] 内容ID
  /// [reportReason] 举报原因
  /// [description] 详细描述（可选）
  static Future<CreateReportResponse> reportContent({
    required int reporterId,
    required int contentId,
    required String reportReason,
    String? description,
  }) async {
    return await createReport(
      reporterId: reporterId,
      reportType: 'content',
      reportReason: reportReason,
      reportedContentId: contentId,
      description: description,
    );
  }
}
